package com.gmall.rabbitmq.consumer.service;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RabbitMQServive_Reliable {

    @RabbitHandler
    @RabbitListener(queues = "Queue_Reliable",concurrency = "1")
    public void receive_SimpleMessage(Channel channal, Message message,String msg){
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        System.out.println("------ Queue_Reliable Start-------");
        System.out.println("MessageID:" + message.getMessageProperties().getMessageId());
        System.out.println("MessageBody:" + new String(message.getBody()));
        System.out.println("msg:" + msg);
        System.out.println("------ Queue_Reliable End-------");

        //从数据库中查询消息ID是否存在 select * from t_message_log where message_id = 'xxx'
        //如果存在，则不进行处理，如果不存在，则进行处理
        //如果处理成功，则进行ACK，如果处理失败，则进行NACK，并且设置requeue为false
        System.out.println("把消息ID保存到数据库中 " +
                        "insert into t_message_log(message_id) values('"+message.getMessageProperties().getMessageId()+"')");
        boolean findMessageID = true;//select

        //int i = 10/0;//网络 抖动
        try {
            if(!findMessageID){
                //
                System.out.println("处理业务");
            }
            channal.basicAck(deliveryTag,false);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                channal.basicNack(deliveryTag,false,true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    @RabbitHandler
    @RabbitListener(queues = "error:queue",concurrency = "1")
    public void receive_ErrorMessage(Channel channal, Message message,String msg) {
        System.out.println("------ error:queue Start 手动处理------");
        System.out.println("MessageID:" + message.getMessageProperties().getMessageId());
        System.out.println("MessageBody:" + new String(message.getBody()));
        System.out.println("msg:" + msg);
        System.out.println("------ error:queue End-------");
    }
}
